package com.study.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.study.pojo.EquipmentBindLog;
import com.study.pojo.EquipmentOperationRecord;
import com.study.service.EquipmentBindLogService;
import com.study.service.EquipmentOperationRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author csc
 * @Date 2023/9/28 16:18
 * @PackageName:com.cscloser.controller
 * @ClassName: ExcelController
 * @Description: TODO
 * @Version 1.0
 */

@RestController
@RequestMapping("/excel")
public class ExcelController {

    @Autowired
    private EquipmentBindLogService bindLogService;

    @Autowired
    private EquipmentOperationRecordService operationRecordService;


    /**
     * 接口直接导出excel
     * @param response
     */
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 准备数据，假设你有一个包含数据的List
        List<EquipmentBindLog> list = bindLogService.list();

        // 设置响应头信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(System.currentTimeMillis()+".xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 使用EasyExcel导出Excel文件
        ExcelWriterBuilder writerBuilder = EasyExcel.write(response.getOutputStream(), EquipmentBindLog.class);
        WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").build();
        writerBuilder.sheet().doWrite(list);
    }

    @GetMapping("/export2")
    public void exportOperationExcel(HttpServletResponse response) throws IOException {
        // 准备数据，假设你有一个包含数据的List
        List<EquipmentOperationRecord> list = operationRecordService.list();

        // 设置响应头信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(System.currentTimeMillis()+".xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 使用EasyExcel导出Excel文件
        ExcelWriterBuilder writerBuilder = EasyExcel.write(response.getOutputStream(), EquipmentOperationRecord.class);
        WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").build();
        writerBuilder.sheet().doWrite(list);
    }


}
